'use strict'

define(function (require, exports, module) {
    var angular = require('angular');
    var dialog = require("dialogplus");
    require("/public/js/plugins/select2/select2");
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    require('/public/js/myservice/contract/contract-common');
    var myMath = require('/public/js/myservice/common/my-math');

    var ContractReceivableRefund = angular.module('ContractReceivableRefund', ['ContractCommonService']);
    ContractReceivableRefund.service('receivableRefundService', ['$rootScope', 'contractCommonService', function ($rootScope, contractCommonService) {
        $rootScope.refundInfo = {};
        $rootScope.editInvoices = [];
        var service = {
            onRefundEditShow: function ($data, $dialog, $dialogScope, refundType, oldRefund, contract, payments) {
                /**
                 * 打开回款编辑界面时初始化
                 * refundType: 1:新增回款，2：修改回款
                 * oldRefund: 原回款
                 * contract : 合同基本信息
                 * payments : 已录入回款信息
                 */
                $dialogScope.busnisseType= contract.busnisseType;

                function edit() {
                    //实收金额变更时，重新计算分摊金额
                    $dialogScope.shareAmount = function () {
                        var items = $dialogScope.editInvoicePayments || [];
                        var refundAmount = ($dialogScope.info.payment_amount || 0);
                        $.each(items, function (i, d) {
                            if (!d._checked || refundAmount <= 0) {
                                d.cur_payment_amount = 0;
                                return true;
                            }
                            d.cur_payment_amount = myMath.sub(d.cur_billing_amount, d.total_payment);
                            refundAmount -= d.cur_payment_amount;
                            if (refundAmount < 0) {
                                d.cur_payment_amount += refundAmount;
                            }
                        });
                    };
                    //默认信息展示
                    contractCommonService.getDisabledInvoice($dialogScope.data.paymentId, function (msg) {
                        msg.input_date = msg.input_date || msg.payment_date;
                        $dialogScope.info = msg;
                        $dialogScope.$applyAsync();
                    });
                    //非查看模式取发票信息
                    contractCommonService.getInvoiceReceivableInfoByContract($data, function (json) {
                        $dialogScope.editInvoicePayments = json;
                        $dialogScope.$applyAsync();
                    });
                }

                if (refundType == 2) {
                    return edit();
                }

                var self = this;
                $dialogScope.onRefundImportNoInvoiceShow = self.onRefundImportNoInvoiceShow;

                $dialogScope.importPayment = function (item) {
                    if (item) {
                        $dialogScope.importPaymentAmount = item.payment_amount;//引入的回款金额
                        $dialogScope.refundInfo = angular.extend(angular.copy(item), {contract_id: $data});
                        $dialogScope.refundInfo.payment_amount = myMath.sub($dialogScope.refundInfo.payment_amount, $dialogScope.refundInfo.have_payment_amount);
                        var temp_input_date = $dialogScope.refundInfo.payment_date;
                        if (contract && contract.input_date) {
                            if (contract.input_date > $dialogScope.refundInfo.payment_date) {
                                temp_input_date = contract.input_date;
                            }
                        }

                        $dialogScope.refundInfo.input_date = util.formatDate(temp_input_date, 'yyyy-MM-dd');                       ;
                    } else {
                        util.alert('请选择回款记录');
                        return false
                    }
                };

                $dialogScope.contractBaseInfo = {contract_id: $data};
                //新建回款
                $dialogScope.refundInfo = {
                    contract_id: $data
                };

                //实收金额变更时，重新计算分摊金额
                $dialogScope.$watch('refundInfo.payment_amount', function () {
                    $dialogScope.shareAmount();
                });

                //分摊回款金额
                $dialogScope.shareAmount = function () {
                    var items = $dialogScope.editInvoicePayments || [];
                    var refundAmount = ($dialogScope.refundInfo.payment_amount || 0);
                    $.each(items, function (i, d) {
                        if (!d._checked || refundAmount <= 0) {
                            d.cur_payment_amount = 0;
                            return true;
                        }
                        d.cur_payment_amount = myMath.sub(d.cur_billing_amount, d.total_payment);
                        refundAmount -= d.cur_payment_amount;
                        if (refundAmount < 0) {
                            d.cur_payment_amount += refundAmount;
                        }
                    });
                };

                $dialogScope.orgianlRefund = oldRefund;
                $dialogScope.refundType = refundType;

                //下拉框设置

                //获取应收信息列表
                if (refundType == 1) {
                    //非查看模式取发票信息
                    contractCommonService.getInvoiceReceivableInfoByContract($data, function (json) {
                        $dialogScope.editInvoicePayments = json;
                        $dialogScope.$applyAsync();
                    });
                }
            },
            onRefundImportNoInvoiceShow: function ($dialogScope, importType, dialog) {
                /**
                 * 引入未开票回款界面初始化
                 */
                $dialogScope.importPayments = [];
                $dialogScope.isloading = true;
                if (importType == 1) {
                    $dialogScope.importType = 1;//引入未开票回款
                    contractCommonService.getContractPaymentHaveAmountByContract($dialogScope.data.contract_id, function (data) {
                        $dialogScope.importPayments = data;
                        $dialogScope.isloading = false;
                        $dialogScope.$applyAsync();

                        setTimeout(function () {
                            dialog.reset();
                        }, 0);
                    })
                } else {
                    $dialogScope.importType = 2;//引入待录入回款
                    contractCommonService.getAccountHkList('', function (data) {
                        $dialogScope.importPayments = data;
                        $dialogScope.isloading = false;
                        $dialogScope.$applyAsync();

                        setTimeout(function () {
                            dialog.reset();
                        }, 0);
                    }, function () {
                        $dialogScope.isloading = false;
                        $dialogScope.$applyAsync();
                    });
                    $dialogScope.search = function (key) {
                        $dialogScope.isloading = true;
                        contractCommonService.getAccountHkList(key, function (data) {
                            $dialogScope.importPayments = data;
                            $dialogScope.isloading = false;
                            $dialogScope.$applyAsync();
                        }, function () {
                            $dialogScope.isloading = false;
                            $dialogScope.$applyAsync();
                        });
                    }
                }

                $dialogScope.selectPayment = function (item) {
                    if($dialogScope.selectedItem){
                        $dialogScope.selectedItem.chkvalue = 0;
                        item.chkvalue = 1;
                        $dialogScope.selectedItem = item;
                    }else {
                        item.chkvalue = 1;
                        $dialogScope.selectedItem = item;
                    }
                };
            },
            editRefundSave: function ($data, $dialog, $dialogScope, callback, contractBaseInfo) {
                /**
                 * 编辑回款
                 */
                var isChkInvoice = true;
                if (contractBaseInfo.business_type == '供应商移动工程协同' || contractBaseInfo.business_type == '供应商线下活动') {
                    isChkInvoice = false;
                }

                function edit() {
                    var checkedInvoices = $.grep($dialogScope.editInvoicePayments || [], function (d, i) {
                        return d._checked == true;
                    });
                    /*if (checkedInvoices.length <= 0) {
                        util.alert('请至少勾选一张发票信息');
                        return false;
                    }*/
                    $dialogScope.info.invoicePayments = checkedInvoices;
                    service.confirmRefundSave($dialogScope.info, $dialog, callback, {
                        isEdit: true,
                        paymentId: $dialogScope.data.paymentId
                    });
                }

                if ($dialogScope.data.edit) {
                    if ($dialogScope.busnisseType == 6 || contractBaseInfo.business_type == '供应商移动工程协同' || contractBaseInfo.business_type == '供应商线下活动') {
                        util.alert('不支持该业务类型的编辑');
                        return false;
                    }
                    return edit();
                }
                /*if (isChkInvoice && $dialogScope.busnisseType != 6 && $dialogScope.data.edit) {
                    return edit();
                }*/

                /**
                 * 保存新增回款
                 */
                var refundInfo = $dialogScope.refundInfo;
                //校验
                if (!refundInfo.finance_code) {
                    util.alert('请先引入回款');
                    return false;
                }

                //实收金额必须小于等于回款金额
                if ($dialogScope.refundInfo.pay_way == '对公' && refundInfo.payment_amount > myMath.sub($dialogScope.importPaymentAmount, $dialogScope.refundInfo.have_payment_amount)) {
                    util.alert('实收金额不能大于未回款金额(' + myMath.sub($dialogScope.importPaymentAmount, $dialogScope.refundInfo.have_payment_amount) + ')');
                    return false;
                }
                if ($dialogScope.importType == 1) {
                    //如果是引入未开票回款，则恢复回款金额
                    refundInfo.payment_amount = $dialogScope.importPaymentAmount;
                }

                if($dialogScope.busnisseType == 6){
                    service.confirmRefundSave(refundInfo, $dialog, callback);
                    return;
                }

                var checkedInvoices = $.grep($dialogScope.editInvoicePayments || [], function (d, i) {
                    return d._checked == true;
                });
                refundInfo.invoicePayments = checkedInvoices;

                //校验
                if ($('.error:visible').length) {
                    return false;
                }

                if(isChkInvoice) {
                    if (checkedInvoices.length > 0) {
                        var not_pay_amount_total = 0;
                        $.each(checkedInvoices, function (key, value) {
                            not_pay_amount_total += myMath.sub(value.cur_billing_amount - value.total_payment);
                        });
                        if (refundInfo.payment_amount > not_pay_amount_total) {
                            util.alert('实收金额不能大于所选发票的待回款金额(' + not_pay_amount_total + ')');
                            return false;
                        } else {
                            service.confirmRefundSave(refundInfo, $dialog, callback);
                        }
                    } else {
                        util.alert('请先绑定发票');

                        return false;
                    }
                }else{
                    service.confirmRefundSave(refundInfo, $dialog, callback);
                }
                return false;
            },

            confirmRefundSave: function (post_data, $dialog, callback, options) {
                var url;
                if (options && options.isEdit) {
                    //url = api_prefix + '/receivable/bind-contract-payment-to-invoice';
                    if (!!post_data.finance_code) {
                        url = api_prefix + "/receivable/save-contract-payment";
                    } else {
                        url = api_prefix + '/receivable/bind-contract-payment-to-invoice';
                    }
                    post_data.payment_id = options.paymentId;
                } else {
                    url = api_prefix + "/receivable/save-contract-payment";
                }
                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    async: false,
                    success: function (json) {
                        if (json.retCode == 0) {
                            util.alert("保存成功");
                            if (callback) {
                                callback();
                            }
                            $dialog.close();
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                            return false;
                        }
                    }
                });

                return false;
            }
            ,
            deleteRefund: function (refundInfo, callback) {
                /**
                 * 删除回款
                 */
                util.confirm('确定要删除此回款吗?', {
                    ok: function () {
                        var post_data = {payment_id: refundInfo.payment_id, Dhk_id: refundInfo.DhkGUID};
                        var url;
                        url = api_prefix + "/receivable/delete-contract-payment";

                        util.myAjax({
                            url: url,
                            type: "POST",
                            context: this,
                            data: post_data,
                            success: function (json) {
                                if (json.retCode == 0) {
                                    refundInfo.__isdelete = 1;
                                    util.alert("删除成功");
                                    $rootScope.$applyAsync();
                                    if (callback) {
                                        callback();
                                    }
                                } else {
                                    util.alert("删除失败：" + json.errMsg);
                                }
                            }
                        });
                    }
                });
            }
        };

        return service;
    }]);

    module.exports = ContractReceivableRefund;
});